<!--
<template>
  <el-form :model="merchantForm" status-icon :rules="rules" ref="merchantForm" label-width="120px" class="demo-ruleForm">
    &lt;!&ndash; 商家名称 - 改为手动填写 &ndash;&gt;
    <el-form-item label="商家名称" prop="merchantName">
      <el-input v-model="merchantForm.merchantName" placeholder="请输入商家名称" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店名称" prop="storeName">
      <el-input v-model="merchantForm.storeName" placeholder="请输入门店名称" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店电话" prop="storePhone">
      <el-input v-model="merchantForm.storePhone" placeholder="请输入门店电话" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="负责人" prop="contactPerson">
      <el-input v-model="merchantForm.contactPerson" placeholder="请输入负责人" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="负责人电话" prop="contactPhone">
      <el-input v-model="merchantForm.contactPhone" placeholder="请输入负责人电话" style="width: 300px"></el-input>
    </el-form-item>

    &lt;!&ndash; 地址联动选择器 &ndash;&gt;
    <el-form-item label="门店地区" prop="address">
      <el-cascader
          v-model="merchantForm.address"
          :options="addressOptions"
          placeholder="请选择地区"
          style="width: 300px"
          :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'children' }"
      ></el-cascader>
    </el-form-item>

    <el-form-item label="详细地址" prop="detailAddress">
      <el-input v-model="merchantForm.detailAddress" placeholder="请输入详细地址" style="width: 300px"></el-input>
    </el-form-item>

    &lt;!&ndash; 坐标输入框与按钮布局优化 &ndash;&gt;
    <el-form-item label="门店坐标" prop="coordinates">
      <el-row :gutter="10">
        <el-col :span="16">
          <el-input v-model="merchantForm.coordinates" readonly style="height: 32px;"></el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" @click="getLocation" style="width: 100%; height: 32px;">获取坐标</el-button>
        </el-col>
      </el-row>
      <div id="map" style="margin-top: 10px; cursor: pointer"></div>
    </el-form-item>

    <el-form-item label="门店图片">
      <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-success="handleStoreImageSuccess"
          :file-list="merchantForm.storeImageList"
          list-type="picture">
        <el-button size="small" type="primary">上传图片</el-button>
      </el-upload>
      <div class="preview-list" v-if="merchantForm.storeImageList.length > 0">
        <el-image v-for="(item, index) in merchantForm.storeImageList" :key="index" :src="item.url" width="100" height="100"
                  @click="previewImage(item.url)"></el-image>
      </div>
    </el-form-item>

    <el-form-item label="门店Logo">
      <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-success="handleStoreLogoSuccess"
          :file-list="merchantForm.storeLogoList"
          list-type="picture">
        <el-button size="small" type="primary">上传图片</el-button>
      </el-upload>
      <div class="preview-list" v-if="merchantForm.storeLogoList.length > 0">
        <el-image v-for="(item, index) in merchantForm.storeLogoList" :key="index" :src="item.url" width="100" height="100"
                  @click="previewImage(item.url)"></el-image>
      </div>
    </el-form-item>

    <el-form-item label="商家简介" prop="description">
      <el-input type="textarea" v-model="merchantForm.description" :rows="4" placeholder="请输入商家简介" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="排序" prop="sortOrder">
      <el-select v-model="merchantForm.sortOrder" placeholder="请选择" style="width: 300px">
        <el-option label="升序" value="asc"></el-option>
        <el-option label="降序" value="desc"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="营业时间" prop="businessHours">
      <el-input v-model="merchantForm.businessHours" placeholder="请输入营业时间" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店状态" prop="status">
      <el-radio-group v-model="merchantForm.status">
        <el-radio :label="1">开启</el-radio>
        <el-radio :label="0">禁用</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('merchantForm')">确定</el-button>
      <el-button @click="resetForm('merchantForm')">重置</el-button>
      <el-button @click="previewForm">预览</el-button>
    </el-form-item>
  </el-form>
</template>

<script>

import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  data() {
    return {
      merchantForm: {
        merchantName: '',
        storeName: '',
        storePhone: '',
        contactPerson: '',
        contactPhone: '',
        address: [],
        detailAddress: '',
        coordinates: '',
        storeImage: '',
        storeImageList: [],
        storeLogo: '',
        storeLogoList: [],
        description: '',
        sortOrder: 'asc',
        businessHours: '',
        status: 1,
      },
      rules: {
        merchantName: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '商家名称长度在2到50个字符之间', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请输入门店名称', trigger: 'blur' }
        ],
        storePhone: [
          { required: true, message: '请输入门店电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入负责人电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        coordinates: [
          { required: true, message: '请获取门店坐标', trigger: 'blur' },
          { pattern: /^-?\d+\.\d+,-?\d+\.\d+$/, message: '请输入正确的坐标格式(纬度,经度)', trigger: 'blur' }
        ],
        storeImage: [
          { required: true, message: '请上传门店图片', trigger: 'change' }
        ],
        storeLogo: [
          { required: true, message: '请上传门店Logo', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入商家简介', trigger: 'blur' },
          { min: 10, message: '商家简介至少10个字符', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ]
      },
      addressOptions: [],
      map: null, // 添加 map 实例变量
      infoWindow: null, // 添加 infoWindow 实例变量
      markers: null // 添加 markers 实例变量
    };
  },
  mounted() {
    this.loadAddressData();
    this.loadAMap(); // 修改为异步加载地图
  },
  methods: {
    // 新增方法：异步加载高德地图
    async loadAMap() {
      try {
        await AMapLoader.load({
          key: '你的高德地图Key',
          version: '2.0',
          plugins: ['AMap.Geolocation', 'AMap.Marker', 'AMap.InfoWindow']
        });
        this.initMap(window.AMap);
      } catch (error) {
        console.error('地图加载失败:', error);
        this.$message.error('地图加载失败');
      }
    },


    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message({ type: 'success', message: '表单提交成功' });
          console.log('表单数据:', this.merchantForm);
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
        this.merchantForm.storeImageList = [];
        this.merchantForm.storeLogoList = [];
      });
    },

    previewForm() {
      this.$refs['merchantForm'].validate((valid) => {
        if (valid) {
          this.$alert(`门店名称: ${this.merchantForm.storeName}<br/>商家名称: ${this.merchantForm.merchantName}`, '表单预览', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          });
        }
      });
    },

    handleStoreImageSuccess(response, file, fileList) {
      this.merchantForm.storeImage = response.url || file.url;
      this.merchantForm.storeImageList = fileList;
      this.$message({ type: 'success', message: '图片上传成功' });
    },

    handleStoreLogoSuccess(response, file, fileList) {
      this.merchantForm.storeLogo = response.url || file.url;
      this.merchantForm.storeLogoList = fileList;
      this.$message({ type: 'success', message: 'Logo上传成功' });
    },

    previewImage(src) {
      this.$imagePreview({ src: src, title: '图片预览' });
    },

    // 修改 initMap 方法，接收 AMap 参数
    initMap(AMap) {
      this.map = new AMap.Map('map', {
        viewMode: '2D',
        zoom: 13,
        center: [116.404, 39.915]
      });

      this.map.on('click', (e) => {
        const lng = e.lnglat.getLng();
        const lat = e.lnglat.getLat();
        const coordinates = `${lat},${lng}`;
        this.merchantForm.coordinates = coordinates;

        this.addMarker([lng, lat], AMap);
        this.showInfoWindow([lng, lat], this.merchantForm.storeName || '当前位置', AMap);
      });
    },

    // 修改 addMarker 方法，接收 AMap 参数
    addMarker(lnglat, AMap) {
      if (this.markers) {
        this.map.remove(this.markers);
      }
      this.markers = new AMap.Marker({
        position: lnglat,
        map: this.map
      });
    },


    // 修改 showInfoWindow 方法，接收 AMap 参数
    showInfoWindow(lnglat, content, AMap) {
      if (this.infoWindow) {
        this.infoWindow.close();
      }
      this.infoWindow = new AMap.InfoWindow({
        content: `<div style="padding: 5px;">${content}</div>`,
        position: lnglat
      });
      this.infoWindow.open(this.map, lnglat);
    },

    getLocation() {
      this.$message({ type: 'info', message: '正在获取您的位置...' });

      if (!window.AMap) {
        this.$message.error('地图未初始化完成');
        return;
      }

      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000
      });

      geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          const lng = result.position.lng;
          const lat = result.position.lat;
          this.merchantForm.coordinates = `${lat},${lng}`;
          this.addMarker([lng, lat], window.AMap);
          this.showInfoWindow([lng, lat], '当前定位位置', window.AMap);
          this.$message({ type: 'success', message: '位置获取成功' });
        } else {
          this.$message.error('获取位置失败');
        }
      });
    },
  }
};
</script>

<style>
#map {
  width: 100%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 10px;
  background-color: #f5f7fa;
}

.preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
}

.preview-list .el-image {
  width: 100px;
  height: 100px;
}
</style>
-->
<template>
  <el-form :model="merchantForm" status-icon :rules="rules" ref="merchantForm" label-width="120px" class="demo-ruleForm">
    <!-- 商家名称 - 改为手动填写 -->
    <el-form-item label="商家名称" prop="merchantName">
      <el-input v-model="merchantForm.merchantName" placeholder="请输入商家名称" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店名称" prop="storeName">
      <el-input v-model="merchantForm.storeName" placeholder="请输入门店名称" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店电话" prop="storePhone">
      <el-input v-model="merchantForm.storePhone" placeholder="请输入门店电话" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="负责人" prop="contactPerson">
      <el-input v-model="merchantForm.contactPerson" placeholder="请输入负责人" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="负责人电话" prop="contactPhone">
      <el-input v-model="merchantForm.contactPhone" placeholder="请输入负责人电话" style="width: 300px"></el-input>
    </el-form-item>

    <!-- 地址联动选择器 -->
    <el-form-item label="门店地区" prop="address">
      <el-cascader
          v-model="merchantForm.address"
          :options="addressOptions"
          placeholder="请选择地区"
          style="width: 300px"
          :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'children' }"
      ></el-cascader>

    </el-form-item>

    <el-form-item label="详细地址" prop="detailAddress">
      <el-input v-model="merchantForm.detailAddress" placeholder="请输入详细地址" style="width: 300px"></el-input>
    </el-form-item>

    <!-- 坐标输入框与按钮布局优化 -->
    <el-form-item label="门店坐标" prop="coordinates">
      <el-row :gutter="10">
        <el-col :span="16">
          <el-input v-model="merchantForm.coordinates" readonly style="height: 32px;"></el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" size="small" @click="getLocation" style="width: 100%; height: 32px;">获取坐标</el-button>
        </el-col>
      </el-row>
      <div id="map" style="margin-top: 10px; cursor: pointer"></div>
    </el-form-item>

    <el-form-item label="门店图片">
      <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-success="handleStoreImageSuccess"
          :file-list="merchantForm.storeImageList"
          list-type="picture">
        <el-button size="small" type="primary">上传图片</el-button>
      </el-upload>
      <div class="preview-list" v-if="merchantForm.storeImageList.length > 0">
        <el-image v-for="(item, index) in merchantForm.storeImageList" :key="index" :src="item.url" width="100" height="100"
                  @click="previewImage(item.url)"></el-image>
      </div>
    </el-form-item>

    <el-form-item label="门店Logo">
      <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-success="handleStoreLogoSuccess"
          :file-list="merchantForm.storeLogoList"
          list-type="picture">
        <el-button size="small" type="primary">上传图片</el-button>
      </el-upload>
      <div class="preview-list" v-if="merchantForm.storeLogoList.length > 0">
        <el-image v-for="(item, index) in merchantForm.storeLogoList" :key="index" :src="item.url" width="100" height="100"
                  @click="previewImage(item.url)"></el-image>
      </div>
    </el-form-item>

    <el-form-item label="商家简介" prop="description">
      <el-input type="textarea" v-model="merchantForm.description" :rows="4" placeholder="请输入商家简介" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="排序" prop="sortOrder">
      <el-select v-model="merchantForm.sortOrder" placeholder="请选择" style="width: 300px">
        <el-option label="升序" value="asc"></el-option>
        <el-option label="降序" value="desc"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="营业时间" prop="businessHours">
      <el-input v-model="merchantForm.businessHours" placeholder="请输入营业时间" style="width: 300px"></el-input>
    </el-form-item>

    <el-form-item label="门店状态" prop="status">
      <el-radio-group v-model="merchantForm.status">
        <el-radio :label="1">开启</el-radio>
        <el-radio :label="0">禁用</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('merchantForm')">确定</el-button>
      <el-button @click="resetForm('merchantForm')">重置</el-button>
      <el-button @click="previewForm">预览</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      merchantForm: {
        merchantName: '',
        storeName: '',
        storePhone: '',
        contactPerson: '',
        contactPhone: '',
        address: [],
        detailAddress: '',
        coordinates: '',
        storeImage: '',
        storeImageList: [],
        storeLogo: '',
        storeLogoList: [],
        description: '',
        sortOrder: 'asc',
        businessHours: '',
        status: 1
      },
      rules: {
        merchantName: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '商家名称长度在2到50个字符之间', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请输入门店名称', trigger: 'blur' }
        ],
        storePhone: [
          { required: true, message: '请输入门店电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入负责人电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        coordinates: [
          { required: true, message: '请获取门店坐标', trigger: 'blur' },
          { pattern: /^-?\d+\.\d+,-?\d+\.\d+$/, message: '请输入正确的坐标格式(纬度,经度)', trigger: 'blur' }
        ],
        storeImage: [
          { required: true, message: '请上传门店图片', trigger: 'change' }
        ],
        storeLogo: [
          { required: true, message: '请上传门店Logo', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入商家简介', trigger: 'blur' },
          { min: 10, message: '商家简介至少10个字符', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ]
      },
      addressOptions: []
    };
  },
  mounted() {

    this.loadAddressData();
    this.initMap();
  },
  methods: {
    getAddressLabels() {
      const [provinceId, cityId, districtId] = this.merchantForm.address;
      const province = this.addressOptions.find(item => item.id === provinceId)?.name || '';
      const city = this.addressOptions
          .find(item => item.id === provinceId)
          ?.children.find(item => item.id === cityId)?.name || '';
      const district = this.addressOptions
          .find(item => item.id === provinceId)
          ?.children.find(item => item.id === cityId)
          ?.children.find(item => item.id === districtId)?.name || '';
      return { province, city, district };
    },
    async loadAddressData() {
      try {
        const res = await this.$axios.get('/web/area/all');
        this.addressOptions = this.buildOptions(res);
      } catch (err) {
        console.error('加载地址失败:', err);
      }
    },

    buildOptions(data) {
      const map = {};
      const roots = [];

      data.forEach(item => {
        map[item.id] = { ...item, children: [] };
      });

      data.forEach(item => {
        if (item.parent_id === 0) {
          roots.push(map[item.id]);
        } else {
          if (!map[item.parent_id]) return;
          map[item.parent_id].children.push(map[item.id]);
        }
      });

      return roots;
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message({ type: 'success', message: '表单提交成功' });
          console.log('表单数据:', this.merchantForm);
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
        this.merchantForm.storeImageList = [];
        this.merchantForm.storeLogoList = [];
      });
    },

    previewForm() {
      this.$refs['merchantForm'].validate((valid) => {
        if (valid) {
          this.$alert(`门店名称: ${this.merchantForm.storeName}<br/>商家名称: ${this.merchantForm.merchantName}`, '表单预览', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          });
        }
      });
    },

    handleStoreImageSuccess(response, file, fileList) {
      this.merchantForm.storeImage = response.url || file.url;
      this.merchantForm.storeImageList = fileList;
      this.$message({ type: 'success', message: '图片上传成功' });
    },

    handleStoreLogoSuccess(response, file, fileList) {
      this.merchantForm.storeLogo = response.url || file.url;
      this.merchantForm.storeLogoList = fileList;
      this.$message({ type: 'success', message: 'Logo上传成功' });
    },

    previewImage(src) {
      this.$imagePreview({ src: src, title: '图片预览' });
    },

    initMap() {
      const map = new AMap.Map('map', {
        zoom: 13,
        center: [116.404, 39.915],
        features: ['bg', 'road', 'point']
      });

      map.on('click', (e) => {
        const lng = e.lnglat.getLng();
        const lat = e.lnglat.getLat();
        const coordinates = `${lat},${lng}`;
        this.merchantForm.coordinates = coordinates;

        this.addMarker([lng, lat]);
        this.showInfoWindow([lng, lat], this.merchantForm.storeName || '当前位置');
      });

      this.map = map;
    },

    addMarker(lnglat) {
      if (this.map.markers) {
        this.map.remove(this.map.markers);
      }

      const marker = new AMap.Marker({
        position: lnglat
      });
      marker.setMap(this.map);
      this.map.markers = marker;
    },

    showInfoWindow(lnglat, content) {
      if (this.infoWindow) {
        this.infoWindow.close();
      }

      this.infoWindow = new AMap.InfoWindow({
        content: `<div style="padding: 5px;">${content}</div>`,
        position: lnglat,
        offset: new AMap.Pixel(0, -30)
      });
      this.infoWindow.open(this.map);
    },

    getLocation() {
      this.$message({ type: 'info', message: '正在获取您的位置...' });

      setTimeout(() => {
        const coordinates = '39.915,116.404';
        this.merchantForm.coordinates = coordinates;
        const [lat, lng] = coordinates.split(',').map(Number);
        this.addMarker([lng, lat]);
        this.showInfoWindow([lng, lat], '当前定位位置');
        this.$message({ type: 'success', message: '位置获取成功' });
      }, 1500);
    }
  }
};
</script>

<style>
#map {
  width: 100%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 10px;
  background-color: #f5f7fa;
}

.preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
}

.preview-list .el-image {
  width: 100px;
  height: 100px;
}
</style>
